﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Web;
using System.Windows.Forms;

namespace Lib
{
    public class Helper
    {
        private static readonly string PunchUrl = "http://cws/cws_home/Welcome.aspx";
        private static readonly string WorkAttendanceUrl = "http://cws/cws_home/Web/Work/FrmAddLateDesc.aspx";
        private static readonly string OnDutyData = "__EVENTTARGET=ctl00%24LinkButton4&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUKLTcwODg1MTE2NmRkSwoNIxF8KOccrbrL57PfhViXnpY%3D&__EVENTVALIDATION=%2FwEWAwLq6svwAQKRkrn2CAKMkrn2CF%2BktkMYwyMeA64pdF2jiSwcCSRH";
        private static readonly string OffDutyData = "__EVENTTARGET=ctl00%24LinkButton3&__EVENTARGUMENT=&__VIEWSTATE=%2FwEPDwUKLTcwODg1MTE2NmRkSwoNIxF8KOccrbrL57PfhViXnpY%3D&__EVENTVALIDATION=%2FwEWAwLq6svwAQKRkrn2CAKMkrn2CF%2BktkMYwyMeA64pdF2jiSwcCSRH";
        private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
        private static readonly string logFilename = "log.txt";
        static StreamWriter writer = null;

        static Helper()
        {
            FileInfo fileInfo = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + logFilename);
            writer = fileInfo.AppendText();
        }

        public static string SendPostData(string url, string data)
        {
            CookieContainer container = new CookieContainer();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.UseDefaultCredentials = true;
            request.CookieContainer = container;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            StreamReader reader = new StreamReader(response.GetResponseStream());
            string text = reader.ReadToEnd();
            response.Close();
            reader.Close();

            request = (HttpWebRequest)WebRequest.Create(url);
            request.CookieContainer = container;
            request.Method = "POST";
            //request.PreAuthenticate = true;
            request.UseDefaultCredentials = true;
            //request.Credentials = CredentialCache.DefaultCredentials;
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = DefaultUserAgent;
            Stream stream = request.GetRequestStream();
            string encodedData = HttpUtility.UrlEncode(data);
            byte[] datas = Encoding.ASCII.GetBytes(data);
            stream.Write(datas, 0, datas.Length);
            stream.Close();
            response = (HttpWebResponse)request.GetResponse();

            reader = new StreamReader(response.GetResponseStream());
            text = reader.ReadToEnd();
            reader.Close();
            return text;
        }

        public static string SendGetData(string url, string data)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.PreAuthenticate = true;
            request.UseDefaultCredentials = true;
            request.Credentials = CredentialCache.DefaultCredentials;
            request.ContentType = "application/x-www-form-urlencoded";
            request.UserAgent = DefaultUserAgent;
            if (!string.IsNullOrEmpty(data))
            {
                Stream stream = request.GetRequestStream();
                byte[] datas = Encoding.UTF8.GetBytes(data);
                stream.Write(datas, 0, datas.Length);
                stream.Close();
            }
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            StreamReader reader = new StreamReader(response.GetResponseStream());
            string text = reader.ReadToEnd();
            reader.Close();
            return text;
        }

        /// <summary>
        /// 上班打卡
        /// </summary>
        public static PunchResult OnDuty()
        {
            string text = SendPostData(PunchUrl, OnDutyData);
            if (text.Contains("打卡成功"))
            {
                return PunchResult.Success;
            }
            else if (text.Contains("重复打卡"))
            {
                return PunchResult.Repeat;
            }
            return PunchResult.Fail;
        }

        /// <summary>
        /// 下班打卡
        /// </summary>
        public static PunchResult OffDuty()
        {
            string text = SendPostData(PunchUrl, OffDutyData);
            if (text.Contains("打卡成功"))
            {
                return PunchResult.Success;
            }
            else if (text.Contains("重复打卡"))
            {
                return PunchResult.Repeat;
            }
            return PunchResult.Fail;
        }

        public static string GetWorkAttendance()
        {
            string text = SendGetData(WorkAttendanceUrl, null);
            return text;
        }

        public static void ShutdowComputer()
        {
            Process p = new Process();
            p.StartInfo = new ProcessStartInfo("shutdown", "/s /f /t 60");
            p.Start();
        }

        /// <summary>
        /// 休眠电脑
        /// </summary>
        public static void SuspendComputer()
        {
            Application.SetSuspendState(PowerState.Suspend, false, false);
        }

        public static void WriterLog(string message)
        {
            writer.WriteLine(DateTime.Now.ToString("yyyyMMdd hh:mm:ss") + " " + message);
            writer.Flush();
        }

        ~Helper()
        {
            writer.Close();
        }
    }
}
